<template>
  <el-dialog :model-value="dialogAdd" width="25%" :before-close="handleClose">
    <template #header>
      <h3 style="padding-bottom: 10px">添加问题</h3>
    </template>
    <el-form :model="form" ref="formRef" :rules="rules" label-width="auto">
      <el-form-item label="问题名称" prop="textKey">
        <el-input
          v-model="form.textKey"
          placeholder="请输入问题名称"
          v-noSpace
          clearable
        />
      </el-form-item>
      <el-form-item label="回答内容" prop="textValue">
        <el-input
          v-model="form.textValue"
          placeholder="请输入回答内容"
          v-noSpace
          clearable
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import { problemModify } from '@/api/Set/set.js';

// 添加用户数据
const form = ref({
  textKey: '',
  textValue: '',
  textType: '1',
});
// 校验规则
const formRef = ref(null);
const rules = {
  textKey: [{ required: true, message: '请输入问题名称', trigger: 'blur' }],
  textValue: [{ required: true, message: '请输入回答内容', trigger: 'change' }],
};

// 定义 props，接收父组件传递的数据
defineProps({
  dialogAdd: {
    type: Boolean,
  },
});

// 定义 emits，向父组件发送事件
const emit = defineEmits(['confirm', 'cancel']);

// 处理取消按钮的点击事件
const handleCancel = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  form.value = {};
  emit('cancel');
};

// 处理确认按钮的点击事件
const handleConfirm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      const res = await problemModify(form.value);
      if (res.data.code === 200) {
        // eslint-disable-next-line no-undef
        ElMessage({
          message: '添加成功',
          type: 'success',
        });
        emit('confirm');
        handleClose();
      } else {
        // eslint-disable-next-line no-undef
        ElMessage({
          message: res.data.msg,
          type: 'error',
        });
      }
    }
  });
};
// 关闭对话框
const handleClose = () => {
  handleCancel();
};

onMounted(() => {});
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
